A function is a routine instruction defined by the programmer. They are not associated with objects. Great examples of functions include the built-in functions.
In [1]:
# Length
len([1,2,4])
Out[1]:
In [2]:
# Convert to Float
float(2.0)
Out[2]:
In [4]:
# Covert to int (truncation)
int(3.9)
Out[4]:
In [8]:
# Create a Set
set()
Out[8]:
In [10]:
# Bool
bool(2 < 3)
Out[10]:
You can define you rown functions using the def keyword. The syntax is as follows:
def func_name(param1, param2...):
// code
// returns if needed
As you would expect, creating your own functions (and later methods) is syntactically painless.
In [11]:
# A function that determines if a number is even or odd.
def even_odd(number):
if number % 2 == 0:
print("{} is even".format(number))
else:
print("{} is odd".format(number))
In [12]:
print(even_odd(19))
In [16]:
# A function that sums up a list
summ = 0
def list_sum(lst):
for item in lst:
summ += item
In [ ]: